import requests
import time
from tkinter import *
import random

lis_text = ['666', '主播真厉害',
            '爱了，爱了',
            '关注走一走，活到99',
            '牛逼！！！',
            '秀儿，是你吗？']


def send():
    a = 0
    while True:
        time.sleep(2)
        send_meg = random.choice(lis_text)
        roomid = entry.get()
        ti = int(time.time())
        url = 'https://api.live.bilibili.com/msg/send'
        data = {
            'color': '16777215',
            'fontsize': '25',
            'mode': '1',
            'msg': send_meg,
            'rnd': '{}'.format(ti),
            'roomid': '{}'.format(roomid),
            'bubble': '0',
            'csrf_token': '08d11cd34efbf3da0d2138d562145e5c',
            'csrf': '08d11cd34efbf3da0d2138d562145e5c',
        }

        headers = {
            'cookie': '_uuid=50D22ECF-208D-9409-DEA1-0B3EA3F74AB793744infoc; buvid3=A0FE83C2-5981-40DC-B0E2-C74A37227ECF155818infoc; rpdid=|(umuummlkY~0J\'ulm|ullmll; sid=kr4i59d5; LIVE_BUVID=AUTO3215909029132687; blackside_state=1; CURRENT_FNVAL=80; DedeUserID=406732493; DedeUserID__ckMd5=48c43aca436bb747; SESSDATA=204f478b%2C1615703177%2C53385*91; bili_jct=08d11cd34efbf3da0d2138d562145e5c; dy_spec_agreed=1; Hm_lvt_8a6e55dbd2870f0f5bc9194cddf32a02=1598946515,1600327358; bp_video_offset_406732493=463816176887860111; _dfcaptcha=90896a21dabbab6ef641f2e393b46913; bsource=search_baidu; PVID=6',
            'origin': 'https://live.bilibili.com',
            'referer': 'https://live.bilibili.com/blanc/1029?liteVersion=true',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
        }
        a += 1
        response = requests.post(url=url, data=data, headers=headers)
        print(response)
        text.insert(END, '第{}条弹幕发送成功'.format(a))
        # 文本框滚动
        text.see(END)
        # 更新
        text.update()
        text.insert(END, '发送内容：{}'.format(send_meg))


root = Tk()
root.title('B站自动发送弹幕')
root.geometry('560x450+400+200')

label = Label(root, text='请输入房间ID:', font=('华文行楷', 20))
label.grid()

entry = Entry(root, font=('隶书', 20))
entry.grid(row=0, column=1)

text = Listbox(root, font=('隶书', 16), width=50, heigh=15)
text.grid(row=2, columnspan=2)

button1 = Button(root, text='开始发送', font=('隶书', 15), command=send)
button1.grid(row=3, column=0)

button2 = Button(root, text='退出程序', font=('隶书', 15), command=root.quit)
button2.grid(row=3, column=1)

root.mainloop()
